package com.dongluhitec.card.deviceUpdeter;

import com.dongluhitec.card.deviceUpdeter.bean.Device;
import com.dongluhitec.card.deviceUpdeter.util.DeviceSearchService;
import com.dongluhitec.card.deviceUpdeter.util.UploadFiles;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.swt.widgets.Composite;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.ProgressBar;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Text;
import com.dongluhitec.card.deviceUpdeter.util.DeviceSearchService.DiscoveryCallback;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.beans.BeanProperties;
import org.eclipse.core.databinding.observable.Realm;
import org.eclipse.jface.databinding.swt.SWTObservables;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.jface.databinding.viewers.ObservableListContentProvider;
import org.eclipse.core.databinding.observable.map.IObservableMap;
import org.eclipse.core.databinding.beans.BeansObservables;
import org.eclipse.jface.databinding.viewers.ObservableMapLabelProvider;
import org.eclipse.core.databinding.observable.list.IObservableList;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.jface.databinding.swt.WidgetProperties;

public class Main extends Shell {
	private DataBindingContext m_bindingContext;
	private final Model model = new Model();

	private Composite composite_left;
	private Composite composite_right;

	private Text txt_filePath;
	private Text text_startIP;
	private Text text_endIp;

	private Button button_stop;
	private Button button_start;
	private ProgressBar progressBar;
	private CheckboxTableViewer checkboxTableViewer;
	private Label label_progressBar;

	public static void main(String args[]) {
		Display display = Display.getDefault();
		Realm.runWithDefault(SWTObservables.getRealm(display), () -> {
            try {
                Display display1 = Display.getDefault();
                Main shell = new Main(display1);
				shell.setText("设备更新");
				shell.setImage(new Image(display1, ClassLoader.getSystemResourceAsStream("logo.png")));
                shell.open();
                shell.layout();
                while (!shell.isDisposed()) {
                    if (!display1.readAndDispatch()) {
                        display1.sleep();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
	}

	public Main(Display display) {
		super(display, SWT.CLOSE | SWT.MIN | SWT.TITLE | SWT.MIN | SWT.RESIZE);
		setLayout(new GridLayout(2, false));

		DeviceSearchService netService = new DeviceSearchService(model);
		UploadFiles uploadFiles = new UploadFiles(model);
		DiscoveryCallback DiscoveryCallback = model::addList;
		netService.setCallback(DiscoveryCallback);


		composite_left = new Composite(this, SWT.BORDER);
		GridData gd_composite = new GridData(GridData.FILL_VERTICAL);
		gd_composite.widthHint = 200;
		composite_left.setLayoutData(gd_composite);

		createLeftComposite(netService);
		
		composite_right = new Composite(this, SWT.BORDER);
		composite_right.setLayoutData(new GridData(GridData.FILL_BOTH));


		createRightComposite(uploadFiles);

		initDataBindings();
	}

	private void createRightComposite(final UploadFiles uploadFiles) {
		composite_right.setLayout(new GridLayout(1,false));

		Composite composite_top = new Composite(composite_right, SWT.NONE);
		composite_top.setLayout(new GridLayout(4,false));
		composite_top.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

		Composite composite_center = new Composite(composite_right, SWT.NONE);
		composite_center.setLayout(new FillLayout());
		composite_center.setLayoutData(new GridData(GridData.FILL_BOTH));

		Composite composite_bottom = new Composite(composite_right, SWT.NONE);
		composite_bottom.setLayout(new GridLayout(1,false));
		composite_bottom.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		
		Label label = new Label(composite_top, SWT.NONE);
		label.setText("上传文件：");

		txt_filePath = new Text(composite_top, SWT.BORDER);
		txt_filePath.setLayoutData(new GridData(GridData.FILL_BOTH));
		txt_filePath.setEditable(false);

		Button button_select = new Button(composite_top, SWT.NONE);
		button_select.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				String path = uploadFiles.choice();
				if(path ==null){
					return;
				}
				txt_filePath.setText(path);
			}
		});
		button_select.setText("选择");

		Button button_upload = new Button(composite_top, SWT.NONE);
		button_upload.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {

				Object[] checkedElements = checkboxTableViewer.getCheckedElements();
				
				if(checkedElements.length==0){
					return;
				}
				List<Device> collect = Arrays.asList(checkedElements).stream().map(map-> (Device)map).collect(Collectors.toList());
				uploadFiles.upload(collect,progressBar);
			}
		});
		button_upload.setText("上传");

		checkboxTableViewer = CheckboxTableViewer.newCheckList(composite_center, SWT.BORDER | SWT.FULL_SELECTION);
		checkboxTableViewer.setAllGrayed(true);
		checkboxTableViewer.setAllChecked(true);
		Table table = checkboxTableViewer.getTable();
		table.setLinesVisible(true);
		table.setHeaderVisible(true);

		TableViewerColumn tableViewerColumn = new TableViewerColumn(checkboxTableViewer, SWT.NONE);
		TableColumn tblclmnNewColumn = tableViewerColumn.getColumn();
		tblclmnNewColumn.setWidth(100);
		tblclmnNewColumn.setText("设备类型");

		TableViewerColumn tableViewerColumn_2 = new TableViewerColumn(checkboxTableViewer, SWT.NONE);
		TableColumn tblclmnNewColumn_2 = tableViewerColumn_2.getColumn();
		tblclmnNewColumn_2.setWidth(110);
		tblclmnNewColumn_2.setText("IP地址");
 
		TableViewerColumn tableViewerColumn_1 = new TableViewerColumn(checkboxTableViewer, SWT.NONE);
		TableColumn tblclmnNewColumn_1 = tableViewerColumn_1.getColumn();
		tblclmnNewColumn_1.setWidth(120);
		tblclmnNewColumn_1.setText("MAC地址");

		TableViewerColumn tableViewerColumn_3 = new TableViewerColumn(checkboxTableViewer, SWT.NONE);
		TableColumn tblclmnNewColumn_3 = tableViewerColumn_3.getColumn();
		tblclmnNewColumn_3.setWidth(74);
		tblclmnNewColumn_3.setText("当前状态");
		
		label_progressBar = new Label(composite_bottom, SWT.NONE);
		label_progressBar.setLayoutData(new GridData(GridData.FILL_BOTH));
		//label_progressBar.setText("正在搜索设备");
		progressBar = new ProgressBar(composite_bottom, SWT.NONE);
		progressBar.setLayoutData(new GridData(GridData.FILL_BOTH));
		progressBar.setToolTipText("当前进度");
		m_bindingContext = initDataBindings();
	}

	private void createLeftComposite(final DeviceSearchService netService) {
		GridLayout layout = new GridLayout(2, false);
		layout.verticalSpacing = 15;
		composite_left.setLayout(layout);

		Label label = new Label(composite_left, SWT.NONE);
		label.setText("起始ip");

		text_startIP = new Text(composite_left, SWT.BORDER);
		text_startIP.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		text_startIP.setText("192.168.1.1");

		Label label_1 = new Label(composite_left, SWT.NONE);
		label_1.setText("截止ip");

		text_endIp = new Text(composite_left, SWT.BORDER);
		text_endIp.setText("192.168.1.255");
		text_endIp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

		
		

		button_start = new Button(composite_left, SWT.NONE);
		GridData layoutData1 = new GridData(SWT.CENTER, SWT.CENTER, true, false, 2, 1);
		layoutData1.widthHint = 150;
		button_start.setLayoutData(layoutData1);
		button_start.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				button_start.setEnabled(false);
				button_stop.setEnabled(true);
				netService.setText_ip(text_startIP.getText());
				netService.setText_ip1(text_endIp.getText());
				netService.start(text_startIP.getText(),text_endIp.getText());
			}
		});
		button_start.setText("开始");
		
		button_stop = new Button(composite_left, SWT.NONE);
		GridData layoutData = new GridData(SWT.CENTER, SWT.CENTER, true, false, 2, 1);
		layoutData.widthHint = 150;
		button_stop.setLayoutData(layoutData);
		button_stop.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				try {
					netService.stop();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				button_start.setEnabled(true);
				button_stop.setEnabled(false);
			}
		});
		button_stop.setText("结束");
	}

	@Override
	protected void checkSubclass() {
		// Disable the check that prevents subclassing of SWT components
	}
	protected DataBindingContext initDataBindings() {
		DataBindingContext bindingContext = new DataBindingContext();
		//
		ObservableListContentProvider listContentProvider = new ObservableListContentProvider();
		IObservableMap[] observeMaps = BeansObservables.observeMaps(listContentProvider.getKnownElements(), Device.class, new String[]{"product", "tyIp", "mac", "status"});
		checkboxTableViewer.setLabelProvider(new ObservableMapLabelProvider(observeMaps));
		checkboxTableViewer.setContentProvider(listContentProvider);
		//
		IObservableList listModelObserveList = BeanProperties.list("list").observe(model);
		checkboxTableViewer.setInput(listModelObserveList);
		//
		IObservableValue observeTextLabel_progressBarObserveWidget = WidgetProperties.text().observe(label_progressBar);
		IObservableValue labelModelObserveValue = BeanProperties.value("label").observe(model);
		bindingContext.bindValue(observeTextLabel_progressBarObserveWidget, labelModelObserveValue, null, null);
		//
		return bindingContext;
	}
}
